package com.hgm.study.viewmodel

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hgm.study.model.serice.UserInfoManager
import com.hgm.study.model.entity.UserInfoEntity
import com.hgm.study.model.serice.UserService
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.security.MessageDigest

/**
 * @author    HGM
 * @version   1.0
 */
class UserViewModel(context: Context) : ViewModel() {

      private val userInfoManager = UserInfoManager(context = context)
      private val userService = UserService.instance()
      var userName by mutableStateOf("")
      var password by mutableStateOf("")


      init {
            viewModelScope.launch {
                  val userName = userInfoManager.userName.firstOrNull()
                  userInfo = if (userName?.isNotEmpty() == true) {
                        UserInfoEntity(userName = userName)
                  } else {
                        null
                  }
            }
      }

      //用户信息
      var userInfo: UserInfoEntity? = null
            private set


      //是否已经登录
      val logged: Boolean
            get() {
                  return userInfo != null
            }

      //是否正在登录
      var loading by mutableStateOf(false)
            private set

      //登录信息
      var error by mutableStateOf("")
            private set


      //登录方法
      suspend fun login(onClose: () -> Unit) {
            loading = true
            error = ""
            delay(1000)
            //模拟网络请求
            val res = userService.signIn(userName = userName, password = md5(password))
            if (res.code == 0 && res.data != null) {
                  userInfo = res.data
                  //userInfoManager.save(userName = "hgm")
                  //登录成功后关闭界面
                  onClose()
            } else {
                  //失败
                  Log.e("hgm", res.message)
                  error = res.message
            }
            loading = false
      }

      //密码加密
      fun md5(content: String): String {
            val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
            val hex = StringBuilder(hash.size * 2)
            for (b in hash) {
                  var str = Integer.toHexString(b.toInt())
                  if (b < 0x10) {
                        str = "0$str"
                  }
                  hex.append(str.substring(str.length - 2))
            }
            return hex.toString()
      }


      fun clear() {
            viewModelScope.launch {
                  userInfoManager.clear()//清除本地数据
                  userInfo = null//置空内存数据
            }
      }
}